package com.tgl.vegetables.plug.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.app.Instrumentation;
import android.content.Context;
import android.graphics.Path;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.io.IOException;
import java.util.List;

public abstract class BaseAccessibilityService implements IAccessibilityService , Handler.Callback {

    private static String TAG = "BaseAccessibilityService";

    protected AccessibilityService mAccessibilityService = null;

    protected static final int MSG_CLICK_EVENT = 1;
    protected static final int DURATION = 100;

    protected static final int WINDOW_HOME = 1;
    protected static final int WINDOW_DIALOG = 2;
    protected static final int WINDOW_ORDER = 3;
    protected static final int WINDOW_SELECT_TIME = 4;

    protected int mCurrentWindow = 0;
    protected boolean mShopCarSelected = false;
    protected Handler mHandler = null;

    protected int mScreenWidth = 0;
    protected int mScreenHeight = 0;

    protected AccessibilityNodeInfo mRootAccessibilityNodeInfo = null;

    public BaseAccessibilityService(){
        mHandler = new Handler(this::handleMessage);
        mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
    }

    protected long getDuration(){
        return DURATION;
    }

    @Override
    public void onInterrupt() {
        mHandler.removeMessages(MSG_CLICK_EVENT);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityService context, AccessibilityEvent accessibilityEvent) {
        if(mScreenWidth <= 0){
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics metrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(metrics);
            mScreenWidth = metrics.widthPixels;
            mScreenHeight = metrics.heightPixels;
        }

        mAccessibilityService = context;
    }

    public AccessibilityNodeInfo findAccessibilityNodeInfo(AccessibilityNodeInfo nodeInfo, String text, int index) {

        if (nodeInfo == null) {
            return null;
        }

        List<AccessibilityNodeInfo> nodeInfos = nodeInfo.findAccessibilityNodeInfosByText(text);
        if (nodeInfos.isEmpty() || index >= nodeInfos.size()) {
            return null;
        }
        return nodeInfos.get(index);
    }

    public AccessibilityNodeInfo findAccessibilityNodeInfoViewId(AccessibilityNodeInfo nodeInfo, String viewId, int index) {

        if (nodeInfo == null) {
            return null;
        }

        List<AccessibilityNodeInfo> nodeInfos = nodeInfo.findAccessibilityNodeInfosByViewId(viewId);
        if (nodeInfos.isEmpty() || index >= nodeInfos.size()) {
            return null;
        }
        return nodeInfos.get(index);
    }

    public boolean performClick(AccessibilityNodeInfo nodeInfo, int depth) {
        if (nodeInfo == null) {
            return false;
        }
        AccessibilityNodeInfo parent = nodeInfo;
        while (depth > 0) {
            parent = parent.getParent();
            if(parent == null){
                break;
            }
            depth--;
        }
        if (parent != null) {
            return parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }
        return false;
    }

    private long lastedTime = 0;

    public void autoClickPoint(final float x, final float y) {
        clickOnScreen(x, y, new AccessibilityService.GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.e(TAG,"onCompleted");
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.e(TAG,"onCancelled");
            }
        },new Handler(Looper.getMainLooper()));
    }

    /**
     * 通过AccessibilityService在屏幕上模拟手势
     * @param path 手势路径
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void gestureOnScreen(Path path, Long startTime, Long duration,
                                AccessibilityService.GestureResultCallback callback,
                                Handler handler){


        GestureDescription.Builder builder = new GestureDescription.Builder();
        builder.addStroke(new GestureDescription.StrokeDescription(         path,startTime,duration));
        GestureDescription gesture = builder.build();
        mAccessibilityService.dispatchGesture(gesture,callback,handler);
    }

    /**
     * 通过AccessibilityService在屏幕上某个位置单击
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void clickOnScreen(Float x, Float y,
                              AccessibilityService.GestureResultCallback callback,
                              Handler handler){

        Path path = new Path();
        path.moveTo(x,y);
        gestureOnScreen(path,0L,1L,callback,handler);
    }

}
